﻿using System.Collections;
using System.Collections.Generic;
using System.Net;
using UnityEngine;
namespace cframework
{
    public static class PythonHttpServer
    {
        private static string GetLocalIPAddress()
        {
            string localIP = "";
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }

            return localIP;
        }

        public static void StartServer(string workDir, int port)
        {
            var pythonPath = DeviceToolPathSetting.GetSystemToolPath("python");
            if (string.IsNullOrEmpty(pythonPath))
            {
                pythonPath = DeviceToolPathSetting.GetSystemToolPath("python3");
            }

            var cmd = $"{pythonPath} -m http.server --bind 0.0.0.0 {port}";

            string command = "";
            bool useBash = true;
            var splitChar = ";";

            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                useBash = false;

                if (useBash)
                {
                    var b = DeviceToolPathSetting.GetSystemToolPath("bash.exe");
                    if (b == null)
                    {
                        useBash = false;
                    }
                }

                if (!useBash)
                {
                    command = "cmd.exe";
                    splitChar = "&";
                }
            }
            else if (Application.platform == RuntimePlatform.OSXEditor)
            {
                command = "osascript";
            }




            var a = $"cd {workDir} {splitChar} {cmd}";

            if (Application.platform == RuntimePlatform.OSXEditor)
            {
                System.Diagnostics.Process.Start(command, $"-e 'tell application \"Terminal\" to do script \"{a}\"'");
            }
            else
            {
                if (useBash)
                {
                    System.Diagnostics.Process.Start(command, $"-c '{a}'");
                }
                else
                {
                    System.Diagnostics.Process.Start(command, $"/k {a}");
                }
            }

            string localIPAddress = GetLocalIPAddress();
            Debug.Log($"Start Python HttpServer: {workDir} => http://{localIPAddress}:{port}");
        }
    }
}